/*
 * $Id: sem.c 50 2009-02-10 05:48:05Z hyunghwan.chung $
 *
   Copyright 2005-2009 Chung, Hyung-Hwan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an  BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#include <xp/bas/sem.h>
#include <xp/bas/memory.h>

xp_sem_t* xp_sem_open (xp_sem_t* sem, unsigned int init)
{
	if (sem == XP_NULL)
	{
		sem = (xp_sem_t*) xp_malloc (XP_SIZEOF(xp_sem_t));
		if (sem == XP_NULL) return XP_NULL;
		sem->__dynamic = xp_true;
	}
	else sem->__dynamic = xp_false;

#if defined(_WIN32)
	sem->hnd = CreateSemaphore (XP_NULL, 
		(LONG)init, XP_TYPE_MAX(LONG), XP_NULL);
	if (sem->hnd == NULL) 
	{
		if (sem->__dynamic) xp_free (sem);
		return XP_NULL;	
	}
#else
	if (sem_init (&sem->hnd, 0, init) == -1)
	{
		if (sem->__dynamic) xp_free (sem);
		return XP_NULL;	
	}
#endif

	return sem;
}

int xp_sem_close (xp_sem_t* sem)
{
#if defined(_WIN32)
	if (CloseHandle(sem->hnd) == 0) return -1;
#else
	if (sem_destroy(&sem->hnd) == -1) return -1;
#endif
	if (sem->__dynamic) xp_free (sem);
	return 0;
}

int xp_sem_acquire (xp_sem_t* sem)
{
#if defined(_WIN32)
	return (WaitForSingleObject (sem->hnd, INFINITE) == WAIT_FAILED)? -1: 0;
#else
	return sem_wait (&sem->hnd);	
#endif
}

int xp_sem_release (xp_sem_t* sem)
{
#if defined(_WIN32)
	return (ReleaseSemaphore (sem->hnd, 1, XP_NULL) == 0)? -1: 0;
#else
	return sem_post (&sem->hnd);	
#endif
}
